package com.DosonLeung.homeschoolcommunication.Controllers;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.DosonLeung.homeschoolcommunication.Constant.UserConstant;
import com.DosonLeung.homeschoolcommunication.Models.UserModel;
import com.DosonLeung.homeschoolcommunication.R;
import com.DosonLeung.homeschoolcommunication.Utils.ImageUtil;
import com.DosonLeung.homeschoolcommunication.Utils.NetWorkUtil;
import com.DosonLeung.homeschoolcommunication.Utils.StorageUtil;

import org.json.JSONException;
import org.json.JSONObject;

import static com.DosonLeung.homeschoolcommunication.Models.SystemModel.getLoginStatus;

/**
 * Created by DosonLeung on 2014/11/7.
 */
public class LoginActivity extends Activity {

    Activity self = this;
    Handler mHandler;
    ProgressDialog pd;
    String password;
    String account;
    String type;
    String avatarPath;

    ImageView loginLogo;
    EditText userName;
    EditText passWord;
    Button loginSubmit;
    Button forgetPassword;
    Button loginRegist;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_activity);
        initFile();
        initHandler();
        initWidgets();
        initValues();
    }

    private void initFile(){
        boolean status = StorageUtil.checkStatus(self);
        if(!status){//如果第一次登录,则为false,否则为true
           Boolean s = StorageUtil.deleteFileFolder(StorageUtil.getBaseDir().toString());
            if(StorageUtil.getBaseDir().mkdirs()) {
               if (StorageUtil.getInfoDir().mkdirs()) {
                   if (StorageUtil.getCameraDir().mkdirs()) {
                       if (StorageUtil.getChatDir().mkdirs()) {
                           StorageUtil.getVoiceDir().mkdirs();
                       } else {
                           Toast.makeText(self, "创建voice失败", Toast.LENGTH_SHORT).show();
                       }
                   } else {
                       Toast.makeText(self, "创建camera失败", Toast.LENGTH_SHORT).show();
                   }
               } else {
                   Toast.makeText(self, "创建info失败", Toast.LENGTH_SHORT).show();
               }
           }else{
                Toast.makeText(self, "创建失败,请重启程序", Toast.LENGTH_SHORT).show();
            }
           Log.e("s",s.toString());
        }
    }

    private void initWidgets(){
        loginLogo = (ImageView)findViewById(R.id.login_logo);
        userName = (EditText)findViewById(R.id.login_userId);
        passWord = (EditText)findViewById(R.id.login_password);
        loginSubmit = (Button)findViewById(R.id.login_submit);
        forgetPassword = (Button)findViewById(R.id.forget_password);
        loginRegist = (Button)findViewById(R.id.regist);
        userName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                loginLogo.setImageResource(R.drawable.login_avatar_background);
            }
        });
        loginSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(NetWorkUtil.getAvailableNetWorkInfo(self)) {
                    if (validate()) {
                        verify();
                    }
                }else{
                    Toast.makeText(self,"您当前的网络不可用",Toast.LENGTH_SHORT).show();
                }
            }
        });
        passWord.setTransformationMethod(PasswordTransformationMethod.getInstance());
        loginRegist.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(NetWorkUtil.getAvailableNetWorkInfo(self)) {
                    Intent intent = new Intent(LoginActivity.this, RegistActivity.class);
                    startActivityForResult(intent, 0);
                }else{
                    Toast.makeText(self,"您当前的网络不可用",Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void initHandler(){
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                /*0x200登陆成功，但可能出现本地没有个人信息的情况，此时菊不会立刻关闭，等待获取个人信息
                 *0x201获取个人信息成功，已经下载好头像
                 *0x401账号或者密码错误
                 *0x404网络超时
                 * 0x600登陆成功后，再获取个人信息成功，但保存失败
                 */
                switch (msg.what) {
                    case 0x200:
                        if (UserConstant.USER_CHARACTER.equals("") || UserConstant.USER_ID.equals("")) {
                            UserModel.getInfoByNetWork(UserConstant.USER_ACCOUNT, UserConstant.USER_PASSWORD, mHandler);
                        } else {
                            stopReflashDialog();
                            startActivity();
                            self.finish();
                        }
                        break;
                    case 0x201:
                        stopReflashDialog();
                        startActivity();
                        self.finish();
                        break;
                    case 0x401:
                        stopReflashDialog();
                        Toast.makeText(LoginActivity.this, "账号或者密码错误", Toast.LENGTH_LONG).show();
                        break;
                    case 0x404:
                        stopReflashDialog();
                        Toast.makeText(LoginActivity.this, "网络超时，请检查你的网络状态", Toast.LENGTH_LONG).show();
                        break;
                    case 0x600:
                        stopReflashDialog();
                        Toast.makeText(LoginActivity.this, "保存信息出现异常，请确定插入SD卡", Toast.LENGTH_LONG).show();
                        break;
                }
            }
        };
    }

    private void initValues() {
        JSONObject jsonObject = UserModel.retrieveInfo();
        if(jsonObject!=null) {
            try {
                avatarPath = jsonObject.getString("avatar_path");
                password = jsonObject.getString("password");
                account = jsonObject.getString("account");
                type = jsonObject.getString("type");
            } catch (JSONException e) {
                e.printStackTrace();
                password = "";
                account = "";
                type = "";
            }
        }else{
            password = "";
            account = "";
            type = "";
        }
        //如果能够从文件获取账号和密码信息，则自动登录
        if(!(password.equals("")||account.equals("")||type.equals(""))){
            ImageUtil.getMyIcon(loginLogo, avatarPath);
            if(getLoginStatus(self)){
                this.showReflashDialog("检测到您的账号，自动登录中");
                UserModel.loginByPassword(account, password, mHandler);
                if (type.equals("1")) {
                    UserConstant.USER_CHARACTER = "patriarch";
                } else if (type.equals("2")) {
                    UserConstant.USER_CHARACTER = "teacher";
                }
            }else{
                userName.setText(account);
            }
        }else{
            password = null;
            account = null;
            type = null;
        }
    }

    //验证输入值是否为空
    private boolean validate(){
        if(userName.getText().toString().equals("")) {
            Toast.makeText(this, "请输入账号", Toast.LENGTH_SHORT).show();
            return false;
        }
        else if(passWord.getText().toString().equals("")){
            Toast.makeText(this,"请输入密码",Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    //检查账号与密码
    private void verify(){
        if(NetWorkUtil.getAvailableNetWorkInfo(self)) {
            this.showReflashDialog("登录中...");
            if(UserConstant.USER_TOKEN=="") {
                this.showReflashDialog("登录中");
                UserModel.loginByPassword(userName.getText().toString(), passWord.getText().toString(), mHandler);
            }
            else
                UserModel.loginByToken(userName.getText().toString(),mHandler);
        }else{
            Toast.makeText(this,"网络超时，请检查您的网络设置",Toast.LENGTH_SHORT).show();
        }
    }

    /*
    * 注册成功后,自动登录
    * */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (requestCode == 0 && resultCode == 0) {
            try {
                Bundle data = intent.getExtras();
                if(data.getBoolean("regist"))
                    UserModel.loginByPassword(UserConstant.USER_ACCOUNT,UserConstant.USER_PASSWORD,mHandler);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void startActivity(){
        Intent intent = new Intent(LoginActivity.this,MainActivity.class);
        startActivity(intent);
        LoginActivity.this.finish();
    }

    /**
     * 显示刷新的时候的等待进度条
     */
    private void showReflashDialog(String msg) {
        this.pd = new ProgressDialog(this);
        this.pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        this.pd.setCancelable(false);
        this.pd.setMessage(msg);
        this.pd.setMax(20);
        this.pd.show();
    }

    /**
     * 结束刷新的时候的等待进度条
     */
    private void stopReflashDialog() {
        if (this.pd != null) {
            pd.dismiss();
        }
    }

    @Override
    public void onDestroy() {
        if(pd!=null)
            if(pd.isShowing()){
                pd.cancel();
                pd.dismiss();
            }
        super.onDestroy();
    }
}
